package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.entity.*
import com.zxy.supplier_system.server.repository.*
import com.zxy.supplier_system.server.utils.orElse404
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
import java.math.BigDecimal
import java.time.OffsetDateTime

@Service
class MarketOrderWithProcurementConvertService(
    private val marketOrderRepository: MarketOrderRepository,
    private val procurementSupplierRepository: ProcurementSupplierRepository,
    private val systemServiceService: SystemServiceService,
    private val marketRepository: MarketRepository,
    private val procurementRepository: ProcurementRepository,
    private val procurementService: ProcurementService,
    private val procurementReceiptRepository:ProcurementReceiptRepository,
    private val marketDeliveryOrderRepository:MarketDeliveryOrderRepository,
    private val marketOrderItemRepository:MarketOrderItemRepository,
    private val employeeOperateRecordService:EmployeeOperateRecordService,
) {

    @Transactional
    fun convertToProcurement(
        marketOrderId: Int,
        procurementSupplierId: Int
    ): Procurement {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        val marketOrder = marketOrderRepository.findByIdAndMarket_SystemService(marketOrderId,currentSystemService).orElse404()
        val procurementSupplier =
            procurementSupplierRepository.findByIdAndSystemService(procurementSupplierId, currentSystemService)
                .orElse404()
        val procurement = Procurement().apply {
            createdDateTime = OffsetDateTime.now()
            this.number = "MOC-"+ marketOrder.number
            // 关键修改点：处理供应商关联
            supplier = procurementSupplier
        }
        procurement.items = marketOrder.goodsList.mapIndexed { index, item ->
            ProcurementItem().apply {
                goods = item.goods
                subGoods = item.subGoods
                amount = item.amount
                unit = item.unit
                val latestItemByProcurementAndItemKey = procurementService.getLatestItemByProcurementAndItemKey(
                    procurementSupplier,
                    item.goods,
                    item.subGoods
                )
                purchasePrice = latestItemByProcurementAndItemKey?.purchasePrice?:goods.costPrice?:BigDecimal.ZERO
                sequence = item.sequence
                note = item.note
                this.procurement = procurement
            }
        }.toMutableList()
        return this.procurementRepository.save(procurement)
    }

    @Transactional
    fun convertToMarketOrder(procurementId: Int,marketId: Int): MarketOrder {
        val systemService = systemServiceService.getCurrentSystemService()
        val procurement = procurementRepository.findByIdAndSupplier_SystemService(procurementId,systemService).orElse404()
        val marketOrder = MarketOrder().apply {
            number = "POC-${procurement.number}"
            employee = procurement.createdBy
            market = marketRepository.findByIdAndSystemService(marketId, systemService).orElse404()
        }
        marketOrder.goodsList = procurement.items.map { item ->
            MarketOrderItem().apply {
                goods = item.goods
                subGoods = item.subGoods
                amount = item.amount
                unit = item.unit
                sequence = item.sequence
                note = item.note
                this.marketOrder = marketOrder
            }
        }.toMutableList()
        return this.marketOrderRepository.save(marketOrder)
    }


    @Transactional
    fun convertToMarketDelivery(receiptId: Int, marketOrderNumber: String): MarketDeliveryOrder {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        val procurementReceipt =
            this.procurementReceiptRepository.findByIdAndProcurement_CreatedBy_SystemService(
                receiptId,
                currentSystemService
            ).orElse404()
        val marketOrder = this.marketOrderRepository.findByNumberAndMarket_SystemService(
            marketOrderNumber,
            systemServiceService.getCurrentSystemService()
        ).orElse404()

        if (marketOrder.submitDateTime == null) {
            throw ResponseStatusException(HttpStatus.BAD_REQUEST, "订单未提交")
        }
        var marketDeliveryOrder = marketDeliveryOrderRepository.save(MarketDeliveryOrder().apply {
            this.market = marketOrder.market
            this.order = marketOrder
            this.id = marketOrder.id
            this.number = marketOrder.number
        })
        marketOrderItemRepository.saveAll(marketOrder.goodsList)
        marketDeliveryOrder = marketDeliveryOrder.apply {
            this.goodsList = procurementReceipt.items.map { item ->
                MarketDeliveryOrderItem().apply {
                    this.order = marketDeliveryOrder
                    this.amount = item.practicalAmount?:item.amount
                    this.goods = item.goods
                    this.unit = item.unit
                    this.subGoods = item.subGoods
                }
            }.toMutableList()
        }
        marketDeliveryOrder = this.marketDeliveryOrderRepository.save(marketDeliveryOrder)
        this.employeeOperateRecordService.deliveryMarketOrder(marketOrder)
        return marketDeliveryOrder
    }

}